//
//  ARVideoFlowCell.m
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/21.
//

#import "ARVideoFlowCell.h"

#import "ARPlayerView.h"
#import "AVPlayerManager.h"
#import "ARVideoWorkCommentCell.h"

#import <Masonry/Masonry.h>
#import <SDWebImage/SDWebImage.h>

#import "AquaRaft-Swift.h"

@interface ARVideoFlowCell () <ARPlayerUpdateDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *container;

@property (nonatomic, strong) UIActivityIndicatorView *loadingView;
@property (nonatomic ,strong) UIImageView *pauseIcon;
@property (nonatomic, strong) ARPlayerView *playerView;

@property (nonatomic, strong) UIImageView *coverImageView;

@property (nonatomic, strong) UIButton *giftBtn;
@property (nonatomic, strong) UIButton *likeBtn;
@property (nonatomic, strong) UIButton *commentBtn;
@property (nonatomic, strong) UIButton *followBtn;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) UITableView *commentTableView;

@property (nonatomic, strong) UITapGestureRecognizer *singleTapGesture;

@property (nonatomic, strong) NSArray <ARVideoWorkCommentCellData *>*commentDataSource;

@end

@implementation ARVideoFlowCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor whiteColor];
        [self initSubViews];
    }
    return self;
}

#pragma mark - UI

- (void)initSubViews {
    //init player view;
    _playerView = [ARPlayerView new];
    _playerView.delegate = self;
    
    //init hover on player view container
    _container = [UIView new];
    _container.backgroundColor = [UIColor clearColor];
    
    _loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
    _loadingView.hidden = NO;
    
    _pauseIcon = [[UIImageView alloc] init];
    _pauseIcon.image = [UIImage imageNamed:@"icon_play_pause"];
    _pauseIcon.contentMode = UIViewContentModeCenter;
    _pauseIcon.layer.zPosition = 3;
    _pauseIcon.hidden = YES;
    
    [self.contentView addSubview:_playerView];
    [self.contentView addSubview:_container];
    [_container addSubview:self.coverImageView];
    [_container addSubview:self.commentTableView];
    [_container addSubview:self.titleLabel];
    [_container addSubview:self.avatarView];
    [_container addSubview:self.followBtn];
    [_container addSubview:self.nameLabel];
    [_container addSubview:self.giftBtn];
    [_container addSubview:self.likeBtn];
    [_container addSubview:self.commentBtn];
    [_container addSubview:_loadingView];
    [_container addSubview:_pauseIcon];
    
    [self.coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.container);
    }];
    
    [_playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [_container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [_pauseIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.height.mas_equalTo(100);
    }];
    
    [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.container);
    }];
    
    [self.commentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(50);
        make.height.mas_equalTo((40 + 24) * 3);
        make.width.mas_equalTo([ARVideoWorkCommentCellData cellWidth]);
    }];
    
    [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(-34);
    }];
    
    [self.followBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.avatarView).offset(1);
        make.width.height.mas_equalTo(14);
    }];

    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.avatarView);
        make.left.equalTo(self.avatarView.mas_right).offset(12);
        make.right.equalTo(self.commentBtn.mas_left).offset(-12);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.avatarView);
        make.right.equalTo(self.nameLabel);
        make.bottom.equalTo(self.avatarView.mas_top).offset(-12);
    }];
    
    [self.commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(34);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-32);
    }];
    
    [self.likeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(34);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(self.commentBtn.mas_top).offset(-24);
    }];
    
    [self.giftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(34);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(self.likeBtn.mas_top).offset(-24);
    }];
    
    _singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
    [_container addGestureRecognizer:_singleTapGesture];
}

-(void)prepareForReuse {
    [super prepareForReuse];
    
    _isPlayerReady = NO;
    [_playerView cancelLoading];
    [_pauseIcon setHidden:YES];
}

#pragma mark - Action

- (void)singleTapAction {
    [self showPauseViewAnim:[_playerView rate]];
    [_playerView updatePlayerState];
}

//暂停播放动画
- (void)showPauseViewAnim:(CGFloat)rate {
    if(rate == 0) {
        [UIView animateWithDuration:0.25f
                         animations:^{
            self.pauseIcon.alpha = 0.0f;
        } completion:^(BOOL finished) {
            [self.pauseIcon setHidden:YES];
        }];
    }else {
        [_pauseIcon setHidden:NO];
        _pauseIcon.transform = CGAffineTransformMakeScale(1.8f, 1.8f);
        _pauseIcon.alpha = 1.0f;
        [UIView animateWithDuration:0.25f delay:0
                            options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.pauseIcon.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
        } completion:^(BOOL finished) {
        }];
    }
}

//加载动画
-(void)startLoadingPlayItemAnim:(BOOL)isStart {
    _loadingView.hidden = !isStart;
    if (isStart) {
        [_loadingView startAnimating];
    } else {
        [_loadingView stopAnimating];
    }
}

/// 礼物按钮点击
- (void)giftBtnClicked:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(videoFlowCellDidClickGiftBtn:)]) {
        [self.delegate videoFlowCellDidClickGiftBtn:self];
    }
}

/// like按钮点击
- (void)likeBtnClicked:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(videoFlowCellDidClickLikeBtn:)]) {
        [self.delegate videoFlowCellDidClickLikeBtn:self];
    }
}

/// comment按钮点击
- (void)commentBtnClicked:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(videoFlowCellDidClickCommentBtn:)]) {
        [self.delegate videoFlowCellDidClickCommentBtn:self];
    }
}

/// follow按钮点击
- (void)followBtnClicked:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(videoFlowCellDidClickFollowBtn:)]) {
        [self.delegate videoFlowCellDidClickFollowBtn:self];
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ARVideoWorkCommentCell *cell = (ARVideoWorkCommentCell *)[tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ARVideoWorkCommentCell class]) forIndexPath:indexPath];
    if (indexPath.row < self.commentDataSource.count) {
        ARVideoWorkCommentCellData *model = self.commentDataSource[indexPath.row];
        [cell setCellData:model];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.commentDataSource.count) {
        ARVideoWorkCommentCellData *model = self.commentDataSource[indexPath.row];
        return model.cellHeight;
    }
    return 0.1;
}

//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.commentTableView.alpha = 1.0;
//    }];
//
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
//}
//
//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
//    [self performSelector:@selector(tableViewHidden) withObject:nil afterDelay:1.0];
//}
//
//- (void)tableViewHidden {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.commentTableView.alpha = 0.3;
//    }];
//}

#pragma mark - ARPlayerUpdateDelegate

-(void)onProgressUpdate:(CGFloat)current total:(CGFloat)total {
    //播放进度更新
}

-(void)onPlayItemStatusUpdate:(AVPlayerItemStatus)status {
    switch (status) {
        case AVPlayerItemStatusUnknown:
            [self startLoadingPlayItemAnim:YES];
            self.coverImageView.hidden = NO;
            break;
        case AVPlayerItemStatusReadyToPlay:
            [self startLoadingPlayItemAnim:NO];
            self.coverImageView.hidden = YES;
            _isPlayerReady = YES;
            
            if(_onPlayerReady) {
                _onPlayerReady();
            }
            break;
        case AVPlayerItemStatusFailed:
            [self startLoadingPlayItemAnim:NO];
            self.coverImageView.hidden = NO;
            _pauseIcon.hidden = NO; // 展示暂停
            break;
        default:
            break;
    }
}

#pragma mark - Video control Function

- (void)play {
    [_playerView play];
    [_pauseIcon setHidden:YES];
}

- (void)pause {
    [_playerView pause];
    [_pauseIcon setHidden:NO];
}

- (void)replay {
    [_playerView replay];
    [_pauseIcon setHidden:YES];
}

- (void)startDownloadBackgroundTask {
    if (_model.videoUrl != nil && _model.videoUrl.length != 0) {
        NSString *playUrl = _model.videoUrl;
        [_playerView setPlayerWithUrl:playUrl];
        return;
    }
    
    // 本地
    NSString *path = [[NSBundle mainBundle] pathForResource:_model.localPath ofType:nil];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [_playerView setPlayerWithUrl:path];
    }
}

- (void)startDownloadHighPriorityTask {
    if (_model.videoUrl != nil && _model.videoUrl.length != 0) {
        NSString *playUrl = _model.videoUrl;
        [_playerView startDownloadTask:[[NSURL alloc] initWithString:playUrl] isBackground:NO];
        return;
    }
    
    // 本地
    NSString *path = [[NSBundle mainBundle] pathForResource:_model.localPath ofType:nil];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [_playerView setPlayerWithUrl:path];
    }
}

#pragma mark - Setter

- (void)setModel:(ARVideoWorkModel *)model {
    _model = model;
    
    self.nameLabel.text = model.author.nickname;
    self.titleLabel.text = model.title;
    
    self.likeBtn.selected = model.isLike;
    
    NSString *avatar = model.author.trueAvatar;
    if (avatar != nil) {
        if ([avatar containsString:@"http"]) {
            [self.avatarView sd_setImageWithURL:[NSURL URLWithString:avatar]];
        } else {
            self.avatarView.image = [UIImage imageWithContentsOfFile:avatar];
        }
    } else {
        self.avatarView.image = nil;
    }
    
    if ([model isCurrentUser]) {
        self.followBtn.hidden = YES;
        self.giftBtn.hidden = YES;
    } else {
        self.followBtn.hidden = [model.author follow];
    }
    
    self.commentDataSource = nil;
    if (!model.comments || model.comments.count == 0) {
        self.commentTableView.hidden = YES;
    } else {
        self.commentTableView.hidden = NO;
        
        NSMutableArray *array = [NSMutableArray array];
        for (ARCommentModel *comment in model.comments) {
            [array addObject:[ARVideoWorkCommentCellData cellDataWithCommentModel:comment]];
        }
        self.commentDataSource = array.copy;
        [self.commentTableView reloadData];
        dispatch_async(dispatch_get_main_queue(), ^{
            CGFloat y = self.commentTableView.contentSize.height - self.commentTableView.frame.size.height;
            if (y < 0) {
                return;
            }
            [self.commentTableView setContentOffset:CGPointMake(0, y) animated:YES];
        });
    }
    
    NSString *localCoverPath = [[NSBundle mainBundle] pathForResource:model.localCover ofType:nil];
    if (localCoverPath && [[NSFileManager defaultManager] fileExistsAtPath:localCoverPath]) {
        self.coverImageView.image = [UIImage imageWithContentsOfFile:localCoverPath];
    }
}

#pragma mark - Getter

- (UIImageView *)coverImageView {
    if (!_coverImageView) {
        _coverImageView = [UIImageView new];
        _coverImageView.contentMode = UIViewContentModeScaleAspectFill;
        _coverImageView.layer.masksToBounds = YES;
    }
    return _coverImageView;
}

- (UIImageView *)avatarView {
    if (!_avatarView) {
        _avatarView = [UIImageView new];
        _avatarView.layer.cornerRadius = 20;
        _avatarView.layer.masksToBounds = YES;
        _avatarView.layer.borderColor = [UIColor whiteColor].CGColor;
        _avatarView.layer.borderWidth = 1;
    }
    return _avatarView;
}

- (UIButton *)followBtn {
    if (!_followBtn) {
        _followBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_followBtn addTarget:self action:@selector(followBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_followBtn setImage:[UIImage imageNamed:@"common_follow_icon"] forState:UIControlStateNormal];
    }
    return _followBtn;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.textColor = [UIColor whiteColor];
        _nameLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    }
    return _nameLabel;
}

- (UIButton *)giftBtn {
    if (!_giftBtn) {
        _giftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_giftBtn addTarget:self action:@selector(giftBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_giftBtn setImage:[UIImage imageNamed:@"common_gift_icon"] forState:UIControlStateNormal];
    }
    return _giftBtn;
}

- (UIButton *)likeBtn {
    if (!_likeBtn) {
        _likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_likeBtn addTarget:self action:@selector(likeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_likeBtn setImage:[UIImage imageNamed:@"common_like_btn_normal"] forState:UIControlStateNormal];
        [_likeBtn setImage:[UIImage imageNamed:@"common_like_btn_selected"] forState:UIControlStateSelected];
    }
    return _likeBtn;
}

- (UIButton *)commentBtn {
    if (!_commentBtn) {
        _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_commentBtn addTarget:self action:@selector(commentBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_commentBtn setImage:[UIImage imageNamed:@"post_detail_commentCount_icon"] forState:UIControlStateNormal];
    }
    return _commentBtn;
}

- (UITableView *)commentTableView {
    if (!_commentTableView) {
        _commentTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_commentTableView registerClass:[ARVideoWorkCommentCell class] forCellReuseIdentifier:NSStringFromClass([ARVideoWorkCommentCell class])];
        _commentTableView.backgroundColor = [UIColor clearColor];
        _commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _commentTableView.delegate = self;
        _commentTableView.dataSource = self;
        
//        _commentTableView.alpha = 0.3;
        _commentTableView.bounces = YES;
        _commentTableView.alwaysBounceVertical = YES;
        _commentTableView.showsVerticalScrollIndicator = NO;
    }
    return _commentTableView;
}

@end
